
import redis

from setting import CABINET_CURRENT_TEMP, CABINET_CURRENT_RSSI_4G, CABINET_CURRENT_LOCK_STATUS, CABINET_CURRENT_RFID_READER_STATUS

from serial_connect import SerialPortMethod

from rssi_4g import Rssi4G

class Abnormal:

    def __init__(self) -> None:
        
        self.r = redis.Redis(host='localhost', port=6379, db=0)

        self.temp = self.get_temp() # 机柜温度

        self.rssi_value = self.get_rssi_4g() # 4g强度

    def get_temp(self) -> float: # 获取温度

        # 下发温度命令

        SerialPortMethod().get_temperature()

        cabinet_current_temp = self.r.get(CABINET_CURRENT_TEMP)

        if cabinet_current_temp:

            cabinet_current_temp = float(cabinet_current_temp.decode())

        else:

            cabinet_current_temp = float(0)

        return cabinet_current_temp

    def get_rssi_4g(self) -> int: # 获取4g信号强度

        with Rssi4G() as rssi:

            rssi_value =  rssi.get_rssi_value()

        if rssi_value:

            rssi_value = int(rssi_value)

        else:

            rssi_value = 0

        self.r.set(CABINET_CURRENT_RSSI_4G, rssi_value)

        return rssi_value
    
    def get_lock_status(self):

        status = self.r.get(CABINET_CURRENT_LOCK_STATUS)

        if not status: # 新启动时

            status = "正常"

        else:

            status = status.decode()

        return status
    
    def get_rfid_reader_status(self):

        status = self.r.get(CABINET_CURRENT_RFID_READER_STATUS)

        if not status: # 新启动时

            status = "正常"

        else:

            status = status.decode()

            if status != "读头异常":

                status = "正常"

        return status

    
    def abnormal(self):

        # 定义状态字典
        data = {
            "rssi_4g": self.rssi_value,
            "cabinet_temp": self.temp,
            "rssi_4g_status": '正常',
            "cabinet_temp_status": '正常',
            "lock_status": self.get_lock_status(),
            "rfid_reader_status": self.get_rfid_reader_status()
        }
        
        # 判断RSSI_4G信号状态
        if self.rssi_value < 31 * 0.2:
            data["rssi_4g_status"] = "信号弱"
        
        # 判断机柜温度状态
        if self.temp >= -5 and self.temp <= 15:
            data["cabinet_temp_status"] = "正常"
        elif self.temp > 15 and self.temp <= 30:
            data["cabinet_temp_status"] = "偏高"
        else:
            data["cabinet_temp_status"] = "异常"

        
        
        return data


if __name__ == "__main__":

    data = Abnormal().abnormal()

    print(data)
